<?php
/**
 * Created by PhpStorm.
 * User: reshared
 * Date: 2017/9/28
 * Time: 下午1:07
 */

namespace Index\Controller;


use Index\Model\SmsCodeModel;
use Index\Repository\SMSRepository;
use Index\Repository\UserRepository;

class AuthController extends BaseController
{
    /**
     * 预检查,全部ajax post
     */
    public function _initialize()
    {
        $this->checkAjaxRequestMethod();
    }

    /**
     * 登录 提交
     */
    public function postLogin()
    {
        $this->hasI(['username', 'password']);
        $username =I('username','','addslashes');
        $password =I('password','');
        $res = UserRepository::instance()->attempt($username, $password);
        if (!$res) {
            $this->ajaxReturn(10009);
        }
        $this->ajaxReturn();
    }

    /**
     * 忘记密码 提交
     */
    public function forgetPassword()
    {
        $this->hasI('username');
        $username = I('username', '', 'addslashes');
        $user = UserRepository::instance()->getByUser($username);
        if (!$user) {
            $this->ajaxReturn(10012);
        }
        //获取验证码
        $res = SMSRepository::instance()->sendForgetCode($username);
        if (!$res) {
            $this->ajaxReturn(10027);
        }
        //设置session并返回结果
        session_set('reset-user', array('uid'=> $user['user_id'], 'username'=>$username));
        $this->ajaxReturn();
    }

    /**
     * 检验验证码
     */
    public function validateCode()
    {
        $this->hasI('code');

        $userCode = I('code');

        if (!$session = session(md5('reset-user'))) {
            $this->ajaxReturn(10005);//系统错误
        }

        $user = UserRepository::instance()->getByUser($session['username']);
        if (!$user) {
            $this->ajaxReturn(10005);//系统错误
        }

        $validate = SMSRepository::instance()->validateCode($userCode, $session['username'], SmsCodeModel::FORGET_MOBILE);
        if(!$validate) {
            $this->ajaxReturn(10003);//验证码不正确
        }
        $this->ajaxReturn();
    }

    /**
     * 重置密码
     */
    public function resetPassword()
    {
        $this->hasI('password');

        $password = I('password');

        if (!$session = session_pull('reset-user')) {
            $this->ajaxReturn(10005);//系统错误
        }

        $r = UserRepository::instance()->resetPassword($session['uid'], $password);

        $this->ajaxReturn((bool)$r);
    }
}